//
//  DestinationScenicViewController.m
//  TravelToHelp
//
//  Created by lanou3g on 15/10/29.
//  Copyright © 2015年 冯贵宾. All rights reserved.
//

#import "DestinationScenicViewController.h"
#import "DestinationScenicModel.h"
#import "DestinationScenicCell.h"
#import "DestinationDetailViewController.h"

@interface DestinationScenicViewController ()<UITableViewDataSource, UITableViewDelegate, MONActivityIndicatorViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *destinationScenicDataArray;
@property (nonatomic, strong) MONActivityIndicatorView *indicatorView;
@property (nonatomic, strong) UIImageView *titleImage;

@property (nonatomic, strong) AppDelegate *app;

@end

@implementation DestinationScenicViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"reloadData" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _app = [[AppDelegate alloc] init];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self addSubView];
    [self addIndicatorView];
    [self setUpData];
    
    [self addInternetObserver];
}
// 通知网络状态
- (void)addInternetObserver
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDataWithInternet:) name:@"reloadData" object:nil];
}

- (void)reloadDataWithInternet:(NSNotification *)notification
{
    [self setUpData];
}




- (void)setUpData
{
    if ([_app internetReachableOrNot]) {
     [_indicatorView startAnimating];
    NSRange rang = NSMakeRange(1, 6);
    NSString *url1 = [self.tempUrl stringByReplacingCharactersInRange:rang withString:@"place"];
    NSString *urlString = [NSString stringWithFormat:@"http://api.breadtrip.com/destination%@pois/all/?sort=default&start=0&sign=2b34502a63e3889ec8b70d962537d585",url1];
    NSString *url = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
   
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30.0];
    [request setHTTPMethod:@"GET"];
    _destinationScenicDataArray = [NSMutableArray array];
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"Httperror: %@%ld", error.localizedDescription, error.code);
            return;
        } else {
            NSDictionary *tempDict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            NSMutableArray *tempArr = [tempDict valueForKey:@"items"];
            for (NSDictionary *dic in tempArr) {
                DestinationScenicModel *model = [[DestinationScenicModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.destinationScenicDataArray addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
               
                [self.tableView reloadData];
                [self.indicatorView stopAnimating];
            });
        }
    }];
    [dataTask resume];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"🙅 您的当前网络中断或网络信号差, 请检查网络后重新进入!!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    }
}

- (void)addSubView
{
    [self setNavigationBar];
    [self addTableView];
}


- (void)setNavigationBar
{
    self.navigationItem.title = @"景点列表";
 
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"backNew.png"] style:(UIBarButtonItemStylePlain) target:self action:@selector(actionLeft:)];
    
    self.navigationItem.leftBarButtonItem = leftButton;
    
}

- (void)actionLeft:(UIBarButtonItem *)leftButton
{
    [self.navigationController popViewControllerAnimated:YES];
}



- (void)addTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 66) style:(UITableViewStylePlain)];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
#pragma mark --设置下拉放大
    self.tableView.contentInset = UIEdgeInsetsMake(210, 0, 0, 0);
    self.titleImage = [[UIImageView alloc] init];
    self.titleImage.contentMode = UIViewContentModeScaleAspectFill;
    self.titleImage.layer.masksToBounds = YES;
    self.titleImage.frame = CGRectMake(0, -210.0f, kScreenWidth, 210);
    [self.titleImage sd_setImageWithURL:[NSURL URLWithString:self.imageUrl] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];;
    // 取消cell中间的横线
    self.tableView.separatorStyle = NO;
    [self.tableView addSubview:self.titleImage];
    
    [self.view addSubview:self.tableView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.destinationScenicDataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"DestinationScenic";
    DestinationScenicCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[DestinationScenicCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
    }
    if (self.destinationScenicDataArray.count > 0) {
        DestinationScenicModel *model = self.destinationScenicDataArray[indexPath.row];
        cell.model = model;
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 130;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    DestinationScenicModel *model = self.destinationScenicDataArray[indexPath.row];
    DestinationDetailViewController *ddVC = [[DestinationDetailViewController alloc] init];
    ddVC.model = model;
    ddVC.imageUrl = model.cover;
    [self.navigationController pushViewController:ddVC animated:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


#pragma mark - 添加加载等待动画
- (void)addIndicatorView
{
    _indicatorView = [[MONActivityIndicatorView alloc] init];
    _indicatorView.center = self.view.center;
    _indicatorView.delegate = self;
    
    _indicatorView.numberOfCircles = 5; // 圆点个数
    _indicatorView.internalSpacing = 5; // 圆点之间的距离
    _indicatorView.radius = 8; // 圆点半径
    //    _indicatorView.delay = 0;
    
    [self.view addSubview:_indicatorView];
  
}

#pragma mark - 加载等待动画的代理方法
- (UIColor *)activityIndicatorView:(MONActivityIndicatorView *)activityIndicatorView circleBackgroundColorAtIndex:(NSUInteger)index
{
    switch (index) {
        case 0:
            return [UIColor redColor];
            break;
        case 1:
            return [UIColor magentaColor];
            break;
        case 2:
            return [UIColor orangeColor];
            break;
        case 3:
            return [UIColor purpleColor];
            break;
        default:
            return [UIColor yellowColor];
            break;;
    }
}




//下拉放大顶部图片
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    CGFloat f = scrollView.contentOffset.y;
    
    if (f < -210) {
        CGRect newF = self.titleImage.frame;
        newF.origin.y = f;
        newF.size.height = -f;
        self.titleImage.frame = newF;
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
